<!-- 
    卡片风格的图片上传组件，主要使用HTML5plus的gallery和Uploader相关API实现
    
    用法：<f7-img-upload title="项目竣工证明" uploadId="files1" :dataKey="EngineeringId"></f7-img-upload>
    
    备注：dataKey，后台AttachmentInfo实体的dataKey，如用户ID，企业ID这些主键
        title，显示的标题
        type，可选，默认值avatar，可上传图片类型，参考后台的AttachmentType枚举来取值
        uploadId，默认值files1，如果一个页面上有多个该组件实例，需要指定为不同的uploadId，
                目前支持的uploadId有10个，files1 ~ files10，参考下面的filesJson，可自行增加
 -->
<template>
  <f7-card>
    <f7-card-header>
      <span>{{ title }}</span>
      <span
        @click="uploadImg"
        class="button col"
      >上传</span>
    </f7-card-header>
    <f7-card-content>
      <f7-list media-list>
        <f7-list-item
          link='#'
          v-for="(file, index) in filesJson[uploadId]"
          :key="file.AttachmentId"
          :title="file.FileName"
          @click="operate(file, index)"
        >
          <img
            slot="media"
            src="../../assets/img/file/jpg.png"
            width="40"
          />
          <div slot="subtitle">
            <span>{{file.FileSize | fileSize}}</span>
            <span class="right">上传成功</span>
          </div>

        </f7-list-item>
      </f7-list>
    </f7-card-content>
  </f7-card>
</template>
<script>
import Config from "../config";
import Upload from "../framework/upload";
import Image from "../framework/image";
import _ from "lodash";

export default {
  props: {
    title: {
      type: String,
      default: ""
    },
    dataKey: {
      type: String
    },
    type: {
      type: String,
      default: "avatar"
    },
    dataType: {
      type: String
    },
    uploadId: {
      // 取值参考下面的filesJson里的数组
      type: String,
      default: "files1"
    }
  },
  data() {
    return {
      filesJson: {
        // 可选择的uploadId，一个页面最多10个文件上传框，可增加
        files1: [],
        files2: [],
        files3: [],
        files4: [],
        files5: [],
        files6: [],
        files7: [],
        files8: [],
        files9: [],
        files10: []
      },
      actionTitle: "",
      actionFileKey: "",
      operateFileIndex: null
    };
  },
  methods: {
    uploadImg() {
      let self = this;
      Image.selectImage("请选择", function(path, needDelete) {
        Image.uploadImage(
          path,
          self.dataKey,
          self.type,
          function(result) {
            if (result) {
              self.filesJson[self.uploadId].push(result.file);
              self.$emit("uploaded", result.fileId);
            }

            // 删除拍摄的照片
            if (needDelete) {
              console.log("删除拍摄的照片");
              Upload.deleteTmpFile(path);
            }
          },
          self.dataType
        );
      });
    },
    operate(file, index) {
      let self = this;
      if (!file.AttachmentId) {
        self.$f7.dialog.alert(
          "文件" + file.FileName + "没有上传成功，无法操作",
          function() {
            self.filesJson[self.uploadId].splice(self.operateFileIndex, 1);
          }
        );
        return;
      }
      let respFile = file;
      self.actionFileKey = respFile.AttachmentId;
      self.actionTitle = file.FileName;
      self.operateFileIndex = index;
      self.$f7.actions
        .create({
          buttons: [
            {
              text: self.actionTitle,
              label: true
            },
            {
              text: "查看",
              bold: true,
              onClick: function() {
                let photos = [];
                _.each(self.filesJson[self.uploadId], attachment => {
                  let url =
                    Config.api.server +
                    Config.api.idDownload +
                    attachment.AttachmentId;
                  photos.push({
                    url: url
                  });
                });

                var photoBrowser = self.$f7.photoBrowser.create({
                  photos: photos,
                  type: "popup"
                });
                photoBrowser.open(index);
                photoBrowser.on("closed", () => {
                  photoBrowser.destroy();
                });
              }
            },
            {
              text: "删除",
              color: "red",
              onClick: function() {
                self.$f7.dialog.confirm(
                  "文件已上传，确定要删除吗？",
                  "删除确认",
                  () => {
                    // 文件可能因类型不符合而没有成功上传，此时直接从页面上删除
                    if (!self.actionFileKey) {
                      self.$f7.dialog.toast("删除成功");
                      self.filesJson[self.uploadId].splice(
                        self.operateFileIndex,
                        1
                      );
                      return;
                    }
                    self.$f7.preloader.show();
                    self.$f7.request.post(
                      Config.api.delFile,
                      { id: self.actionFileKey },
                      r => {
                        self.$f7.preloader.hide();
                        self.filesJson[self.uploadId].splice(
                          self.operateFileIndex,
                          1
                        );
                        self.$f7.dialog.toast("删除成功");
                      }
                    );
                  }
                );
              }
            }
          ]
        })
        .open();
    },
    getThumb(file) {
      if (file.FileName) {
        let extension = file.FileName.substring(
          file.FileName.lastIndexOf(".") + 1
        );
        if (
          extension &&
          "avi,doc,docx,jpg,mp4,pdf,png,ppt,pptx,rar,txt,xls,xlsx,zip"
            .split(",")
            .includes(extension.toLowerCase())
        ) {
          return "/static/img/file/" + extension.toLowerCase() + ".png";
        }
      }
      return "/static/img/file/default.png";
    }
  }
};
</script>
<style scoped>
</style>